#include "selectBox.h"

/**
 * @param imageName The file name of the image of the parking lot
 * @param windowName The name of the window
 */
selectBox::selectBox(String imageName, String windowName){
    drawing_box = false;
    this->windowName = windowName;
    box = cvRect(-1, -1, 0, 0);
    image = cvLoadImage(imageName.c_str());
    temp = cvCloneImage(image);
    cvNamedWindow(this->windowName.c_str());
    cv::setMouseCallback(this->windowName.c_str(),wrappedOnMouse,(void*)this);
}

vector<CvRect> selectBox::draw(){
    // main loop
    while (1) {
        cvCopyImage(image, temp);
        if (drawing_box)
            draw_box(temp, box);
        cvShowImage(windowName.c_str(), temp);
        // wait until user hits enter
        if (cvWaitKey(15) == 27)
            break;
    }
    cvReleaseImage(&image);
    cvReleaseImage(&temp);
    cvDestroyWindow(windowName.c_str());
    
    return rectangles;
}

void selectBox::draw_box(IplImage* img, CvRect rect){
        cvRectangle(img, cvPoint(box.x, box.y), cvPoint(box.x + box.width, box.y + box.height),
            cvScalar(0x00, 0xff, 0x00), 1, CV_AA);
}

void selectBox::my_mouse_callback(int event, int x, int y, int flags){
    //IplImage* image = (IplImage*) param;
    
    switch (event) {
        case CV_EVENT_MOUSEMOVE:
            if (drawing_box) {
                box.width = x - box.x;
                box.height = y - box.y;
            }
            break;
        case CV_EVENT_LBUTTONDOWN:
                drawing_box = true;
                box = cvRect(x, y, 0, 0);
            break;
        case CV_EVENT_LBUTTONUP:
                drawing_box = false;
                if (box.width < 0) {
                    box.x += box.width;
                    box.width *= -1;
                }
                if (box.height < 0) {
                    box.y += box.height;
                    box.height *= -1;
                }
                // instead of printing it, store it in vector, linked list, etc.
		// COORDINETS SELECTED <- PUT INTO VECTOR
                cout << "Rectangle coord: X " << box.x << " Y:" << box.y << " width:" << box.width << " height:" << box.height << endl;
                rectangles.push_back(cvRect(box.x,box.y,box.width,box.height));
                draw_box(image, box);
            break;
    }
}

void wrappedOnMouse(int event, int x, int y, int flags, void* ptr) {
    selectBox* mcPtr = (selectBox*)ptr;
    if (mcPtr != NULL)
        mcPtr->my_mouse_callback(event, x, y, flags);
}
